<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="品牌名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="客户姓名" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="是否显示" prop="status">
        <el-select v-model="queryParams.status" placeholder="是否显示" clearable size="mini">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPerm="['beauty:brand:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPerm="['beauty:brand:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPerm="['beauty:brand:remove']">删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" :height="tableHeight">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="expand">
        <template slot-scope="{row}">
          <el-form>
            <el-form-item label="描述:">
              <span v-html="row.bdesc"></span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="品牌标志" align="center" prop="logo" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.logo==''">暂无</span>
          <el-image v-else :src="scope.row.logo" style="width: 80px; height: 45px" fit="fill"
                    :preview-src-list="[scope.row.logo]"/>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否显示">
        <template slot-scope="{row}">
          <el-tag v-if="row.status === 1" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPerm="['beauty:brand:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPerm="['beauty:brand:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                @pagination="getList"/>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="品牌标志" prop="logo">
              <el-upload class="up-img-uploader" :action="imageAction" :show-file-list="false"
                         :on-success="handleUploadSuccess" :headers="headers">
                <img v-if="imageUrl" :src="imageUrl" class="up-img" alt="">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="品牌名称" prop="name">
              <el-input v-model="form.name" placeholder="品牌名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" style="width: 50%" controls-position="right" placeholder="排序"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="是否显示" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusOptions" :key="dict.value" :label="+dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="商品分类" prop="productCategoryIds">
              <el-select v-model="form.productCategoryIds" style="width: 100%" multiple placeholder="请选择分类"
                         @change="optionChange" clearable
                         filterable>
                <el-option v-for="item in productCategoryList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="描述">
              <editor v-model="form.bdesc" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Editor from '@c/Editor'
import {
  listBrand,
  updateBrand,
  addBrand,
  delBrand, getBrand
} from '@a/beauty/brand'
import { getToken } from '@u/auth'
import { getSecondLevelProductCategories } from '@a/beauty/productCategory'

export default {
  name: 'brand',
  components: {
    Editor
  },
  data() {
    return {
      // 保险时间
      insuranceDateRange: [],
      imageUrl: null, // 上传图片回显
      headers: {
        // 上传文件的请求头
        Authorization: 'Bearer ' + getToken()
      },
      // 请求地址
      imageAction: process.env.VUE_APP_BASE_API + process.env.VUE_APP_FILE_UPLOAD, // 上传的图片服务器地址
      tableHeight: window.innerHeight - 340,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '品牌名称不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        logo: [
          { required: true, message: '品牌标志不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '是否显示不能为空', trigger: 'blur' }
        ],
        productCategoryIds: [
          { required: true, message: '商品分类不能为空', trigger: 'blur' }
        ]
      },
      // 商品分类列表
      productCategoryList: []
    }
  },
  created() {
    this.getList()
    this.getDictItems('beauty_brand_status').then(response => {
      this.statusOptions = response.data
    })
    // 获取商品分类列表 只要3级分类商品
    getSecondLevelProductCategories().then(res => {
      this.productCategoryList = res.data
    })
  },
  methods: {
    /**
     * 解决不回显问题
     */
    optionChange() {
      this.$forceUpdate()
    },
    /** 上传封面成功 **/
    handleUploadSuccess(res, file) {
      // console.log(res)
      if (res.code == 200) {
        const { url } = res.data
        this.msgNoticeSuccess('上传成功')
        this.imageUrl = url
        this.form.logo = url
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listBrand(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加品牌'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getBrand(id).then(response => {
        this.form = response.data
        // 回显图片
        this.imageUrl = this.form.logo
        this.open = true
        this.title = '修改品牌'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateBrand(this.form).then(response => {
              this.msgNoticeSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addBrand(this.form).then(response => {
              this.msgNoticeSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delBrand(ids)
      }).then(() => {
        this.getList()
        this.msgNoticeSuccess('删除成功')
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        sort: 0,
        logo: undefined,
        bdesc: undefined,
        productCategoryIds: undefined,
        status: 0
      }
      this.imageUrl = null
      this.resetForm('form')
    }
  }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.up-img-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #000000;
  background-color: #e8e8e8;
  width: 170px;
  height: 170px;
  line-height: 170px;
  text-align: center;
}

.up-img {
  width: 170px;
  height: 170px;
  display: block;
}


.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
